﻿<%@ WebHandler Language="C#" Class="v" %>

using System;
using System.Web;
using Com.Toook.Common;
using System.Data.SQLite;

/// <summary>
/// 记录用户访问记录。进入时间，退出时间。
/// </summary>
public class v : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        //string time = context.Request["t"];
        //if (time != null)
        //{
        //    DateTime inTime;
        //    if (DateTime.TryParse(context.Request["t"], out inTime))
        //    {
        //        SaveVisitRecord(context, inTime);
        //    }
        //}
        SaveVisitRecord(context);
        context.Response.Write("OK");
    }
    /// <summary>
    /// 保存用户访问记录
    /// </summary>
    private void SaveVisitRecord(HttpContext context)//, DateTime inTime
    {
        string jsInTime = context.Request["tj"];
        string jsOutTime = context.Request["tje"];
        DateTime ji;
        DateTime jo;
        string stayTime = "0";
        if (DateTime.TryParse(jsInTime, out ji) && DateTime.TryParse(jsOutTime, out jo))
        {
            TimeSpan ts = jo - ji;
            stayTime = ts.Hours.ToString() + ":" + ts.Minutes.ToString() + ":" + ts.Seconds.ToString();
        }
        
        DateTime outTime = DateTime.Now;
        //用window.unload方法，refer是关闭的页面地址. RawUrl都是v.ashx
        string url = context.Request.UrlReferrer == null ? "no" : context.Request.UrlReferrer.PathAndQuery;//context.Request.RawUrl;
        string ip = context.Request.UserHostAddress;
        string agent = context.Request.UserAgent;
        string command = "insert into UserVisitRecord(ip, stay, agent, url) "
                + " values(@ip, @stay, @agent, @url) ";
        SQLiteConnection con = SqliteHelper.GetConnection("SQLiteDatabase");
        SQLiteCommand cmd = new SQLiteCommand(command, con);
        cmd.Parameters.Add("@ip", System.Data.DbType.String, 15).Value = ip;
        cmd.Parameters.Add("@stay", System.Data.DbType.String).Value = stayTime;        
        cmd.Parameters.Add("@agent", System.Data.DbType.String, 200).Value = agent.Length > 200 ? agent.Substring(0, 200) : agent;
        cmd.Parameters.Add("@url", System.Data.DbType.String, 200).Value = url;
        
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            LogHelper.Log.Error("SaveVisitRecord保存访问记录错误", ex);
        }
        finally
        {
            SqliteHelper.CloseDbResource(con, null);
        }

    }
    public bool IsReusable {
        get {
            return false;
        }
    }

}